<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-title">WeddingManagerSystem</div>
      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="用户名密码登录">
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" @input="handleInput('loginForm', 'username', $event)" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" @input="handleInput('loginForm', 'password', $event)" />
            </el-form-item>
            <el-form-item class="login-actions">
              <el-checkbox v-model="rememberMe">记住我</el-checkbox>
              <el-link type="primary" :underline="false" @click="goToForgotPassword">忘记密码?</el-link>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="login-btn" @click="handleLogin">登录</el-button>
            </el-form-item>
            <div class="register-link">
              还没有账号? <el-link type="primary" :underline="false" @click="goToRegister">立即注册</el-link>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="邮箱验证码登录">
          <el-form ref="phoneLoginForm" :model="phoneLoginForm" :rules="phoneLoginRules" class="login-form">
            <el-form-item prop="email">
              <el-input v-model="phoneLoginForm.email" type="email" placeholder="请输入邮箱" prefix-icon="Message" @input="handleInput('phoneLoginForm', 'email', $event)" />
            </el-form-item>
            <el-form-item prop="code">
              <el-input v-model="phoneLoginForm.code" placeholder="请输入验证码" prefix-icon="Message" @input="handleInput('phoneLoginForm', 'code', $event)">
                <template #suffix>
                  <el-button type="text" @click="getCode" :disabled="countDown > 0">{{ countDown > 0 ? `${countDown}秒后重新获取` : '获取验证码' }}</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="login-btn" @click="handlePhoneLogin">登录</el-button>
            </el-form-item>
            <div class="register-link">
              还没有账号? <el-link type="primary" :underline="false" @click="goToRegister">立即注册</el-link>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';

// 添加输入处理函数，确保输入值立即更新
const handleInput = (formName, field, value) => {
  console.log(`更新${formName}.${field}:`, value);
  if (formName === 'loginForm') {
    loginForm[field] = value;
  } else if (formName === 'phoneLoginForm') {
    phoneLoginForm[field] = value;
  }
};

import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '../utils/request';

const router = useRouter();
const activeTab = ref('0');
const rememberMe = ref(false);
const countDown = ref(0);

const loginForm = reactive({
  username: '',
  password: ''
});

const phoneLoginForm = reactive({
      email: '',
      code: ''
    });

// 修改验证触发方式为input和blur，提高响应速度
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: ['input', 'blur'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: ['input', 'blur'] },
    { min: 6, message: '密码长度不能小于6位', trigger: ['input', 'blur'] }
  ]
};

// 移除空的输入处理函数，使用组件默认处理

const phoneLoginRules = {
    email: [
      { required: true, message: '请输入邮箱', trigger: ['input', 'blur'] },
      { pattern: /^[0-9a-zA-Z_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱格式', trigger: ['input', 'blur'] }
    ],
    code: [
      { required: true, message: '请输入验证码', trigger: ['input', 'blur'] },
      { len: 6, message: '验证码长度为6位', trigger: ['input', 'blur'] }
    ]
  };

const handleLogin = async () => {
  try {
    const username = loginForm.username;
    const password = loginForm.password;
    const response = await request.post('/login', { username, password });
    if (response.success) {
      // 保存token
      localStorage.setItem('token', response.data.token);
      // 记住密码
      if (rememberMe.value) {
        localStorage.setItem('username', username);
      } else {
        localStorage.removeItem('username');
      }
      ElMessage.success('登录成功');
      router.push('/');
    } else {
      ElMessage.error(response.message || '登录失败');
    }
  } catch (error) {
    ElMessage.error('登录失败，请重试');
  }
};

const handlePhoneLogin = async () => {
    try {
      const email = phoneLoginForm.email;
      const code = phoneLoginForm.code;
      const response = await request.post('/user/loginByEmail', { email, code });
      if (response.code === 200) {
        // 保存token
        localStorage.setItem('token', response.data.token);
        ElMessage.success('登录成功');
        router.push('/');
      } else {
        ElMessage.error(response.message || '登录失败');
      }
    } catch (error) {
      ElMessage.error('登录失败，请重试');
    }
  };

const getCode = () => {
    const email = phoneLoginForm.email;
    if (!email || !/^[0-9a-zA-Z_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)) {
      ElMessage.warning('请输入正确的邮箱');
      return;
    }

    // 实际调用发送验证码接口
    request.post('/user/sendCode', { email }).then(res => {
      if (res.code === 200) {
        ElMessage.success('验证码发送成功，请注意查收');
        countDown.value = 60;
        const timer = setInterval(() => {
          countDown.value--;
          if (countDown.value <= 0) {
            clearInterval(timer);
          }
        }, 1000);
      } else {
        ElMessage.error(res.message || '验证码发送失败');
      }
    }).catch(error => {
      ElMessage.error('验证码发送失败，请重试');
    });
  };

const goToRegister = () => {
  router.push('/user/register');
};

const goToForgotPassword = () => {
  router.push('/forgot-password');
};

// 页面加载时，检查是否记住了用户名
onMounted(() => {
  const savedUsername = localStorage.getItem('username');
  if (savedUsername) {
    loginForm.username = savedUsername;
    rememberMe.value = true;
  }
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 原生输入框样式 */
.native-input-wrapper {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 15px;
  height: 40px;
  transition: border-color 0.3s;
}

.native-input-wrapper:focus-within {
  border-color: #4096ff;
  outline: none;
}

.input-icon {
  margin-right: 10px;
  color: #909399;
}

.native-input {
  flex: 1;
  height: 100%;
  border: none;
  outline: none;
  font-size: 14px;
}

.with-suffix {
  position: relative;
  padding-right: 110px;
}

.code-button {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #4096ff;
  cursor: pointer;
  font-size: 14px;
  padding: 0;
}

.code-button:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.login-card {
  width: 400px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  overflow: hidden;
}

.login-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin: 20px 0;
  color: #303133;
}

.login-tabs {
  margin: 0 20px;
}

.login-form {
  padding: 20px;
}

.login-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.login-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.register-link {
  text-align: center;
  margin-top: 15px;
  color: #606266;
}
</style>